import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'

export class XiuXianSect extends plugin {
    constructor() {
        super({
            name: '修仙文游宗门',
            dsc: '修仙游戏的宗门相关功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^创建宗门(.*)$', fnc: 'createSect' },
                { reg: '^加入宗门(.*)$', fnc: 'joinSect' },
                { reg: '^查看宗门$', fnc: 'showSect' },
                { reg: '^宗门修炼$', fnc: 'sectCultivation' },
                { reg: '^宗门升级$', fnc: 'upgradeSect' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
    }

    async createSect(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        if (player.sect) return this.reply('你已经加入了宗门,无法创建新的宗门')

        const sectName = e.msg.replace(/^创建宗门/, '').trim()
        if (!sectName) return this.reply('请输入宗门名称')

        if (this.data.sects[sectName]) {
            return this.reply('该宗门名称已存在,请选择其他名称')
        }

        this.data.sects[sectName] = {
            name: sectName,
            leader: player.name,
            members: [player.name],
            level: 1,
            resources: 0
        }

        player.sect = sectName

        this.utils.saveJSON(this.data.paths.sects, this.data.sects)
        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)

        return this.reply(`恭喜你成功创建宗门"${sectName}"!`)
    }

    async joinSect(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        if (player.sect) return this.reply('你已经加入了宗门,无法加入其他宗门')

        const sectName = e.msg.replace(/^加入宗门/, '').trim()
        if (!sectName) return this.reply('请输入要加入的宗门名称')

        const sect = this.data.sects[sectName]
        if (!sect) return this.reply('该宗门不存在')

        const maxMembers = 10 + (sect.level - 1) * 5
        if (sect.members.length >= maxMembers) {
            return this.reply(`该宗门成员已达上限(${maxMembers}人),无法加入`)
        }

        sect.members.push(player.name)
        player.sect = sectName

        this.utils.saveJSON(this.data.paths.sects, this.data.sects)
        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)

        return this.reply(`你已成功加入宗门"${sectName}"!`)
    }

    async showSect(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        if (!player.sect) return this.reply('你还没有加入宗门')

        const sect = this.data.sects[player.sect]
        const sectText = `
    宗门名称: ${sect.name}
    宗门等级: ${sect.level}
    宗主: ${sect.leader}
    成员数量: ${sect.members.length}
    宗门资源: ${sect.resources}
    
    成员列表:
    ${sect.members.join(', ')}
        `.trim()

        const forwardMsg = await this.utils.markdown(e, sectText, '宗门信息')
        return this.reply(forwardMsg)
    }

    async sectCultivation(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        if (!player.sect) return this.reply('你还没有加入宗门,无法进行宗门修炼')

        const sect = this.data.sects[player.sect]
        if (!sect) return this.reply('宗门信息异常,请联系管理员')

        if (this.utils.isOnCD(player, '宗门修炼')) {
            return this.reply(`宗门修炼还在冷却中,剩余${this.utils.getRemainingCDTime(player, '宗门修炼')}分钟`)
        }

        const requiredEnergy = 20
        if (player.energy < requiredEnergy) {
            return this.reply(`灵力不足,无法进行宗门修炼。需要${requiredEnergy}点灵力,当前灵力:${player.energy}`)
        }

        const baseExp = 20
        const baseLingshi = 10
        const levelBonus = sect.level * 0.1
        const expGain = Math.floor(baseExp * (1 + levelBonus))
        const lingshiGain = Math.floor(baseLingshi * (1 + levelBonus))

        player.exp += expGain
        player.lingshi += lingshiGain
        player.energy -= requiredEnergy

        sect.resources += Math.floor(lingshiGain * 0.1)

        this.utils.setCD(player, '宗门修炼', 60)

        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
        this.utils.saveJSON(this.data.paths.sects, this.data.sects)

        this.utils.updateTaskProgress(player, '宗门修炼')

        return this.reply(`宗门修炼完成!获得${expGain}点经验和${lingshiGain}灵石。消耗${requiredEnergy}点灵力。宗门获得${Math.floor(lingshiGain * 0.1)}点资源。`)
    }

    async upgradeSect(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        if (!player.sect) return this.reply('你还没有加入宗门，无法进行宗门升级')

        const sect = this.data.sects[player.sect]
        if (!sect) return this.reply('宗门信息异常，请联系管理员')

        if (sect.leader !== player.name) return this.reply('只有宗主才能进行宗门升级')

        const upgradeCost = sect.level * 1000
        if (sect.resources < upgradeCost) return this.reply(`宗门资源不足，升级到${sect.level + 1}级需要${upgradeCost}资源`)

        sect.resources -= upgradeCost
        sect.level++

        this.utils.updateSectAttributes(sect)

        this.utils.saveJSON(this.data.paths.sects, this.data.sects)

        const upgradeInfo = this.utils.getSectUpgradeInfo(sect.level)
        return this.reply(`宗门升级成功！当前等级: ${sect.level}, 剩余资源: ${sect.resources}\n${upgradeInfo}`)
    }
}
